package leetcode.simple.q206;

/**
 * 206. 反转链表
 */
public class Main {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        ListNode listNode = createListNode(nums);
        ListNode reverse = reverseList(listNode);
        System.out.println(reverse);
    }

    public static ListNode reverseList(ListNode head) {
        if (head == null){
            return null;
        }

        //创建一个新链表，使用头插法将旧链表的值存进去
        //ListNode newList = new ListNode(head.val);
        ListNode pointer = head;
        ListNode newList = null;
        while (true){

            //头插法
            ListNode node = new ListNode(pointer.val);
            node.next = newList;
            newList = node;

            if (pointer.next != null){
                //链表后移
                pointer = pointer.next;
            }else {
                break;
            }
        }

        return newList;
    }

    /**
     * 创建链表
     * @param nums
     * @return
     */
    public static ListNode createListNode(int[] nums){
        //将第一个数作为头结点
        ListNode listNode = new ListNode(nums[0]);
        ListNode pointer = listNode;

        for (int i = 1; i < nums.length; i++) {
            //找尾结点
            while (pointer.next != null){
                //往后移动
                pointer = pointer.next;
            }

            //找到尾结点后添加数据
            pointer.next = new ListNode(nums[i]);
        }

        return listNode;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
